package com.lagou.wang.servlet.user;

import com.lagou.wang.pojo.Student;
import com.lagou.wang.pojo.User;
import com.lagou.wang.service.user.UseService;
import com.lagou.wang.service.user.UserServiceImpl;
import com.lagou.wang.servlet.student.StudentServlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "LoginServlet", urlPatterns = "/jsp/userServlet")
public class LoginServlet extends HttpServlet {

    //创建StudentService对象
    UseService userService  = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String param = request.getParameter("param");
        if (param.equals("login")){
            this.login(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 1.获取请求中的用户名和密码信息
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        //2.创建UserService类型的对象去实现数据的校验功能
        UseService userService  = new UserServiceImpl();
        User user = userService.userLoginService(new User(userName, password));
        if (null == user) {
            request.setAttribute("msg", "登录失败，用户名或密码错误！");
            // 实现服务器跳转  共享request和response对象
            request.getRequestDispatcher("login.jsp").forward(request, response);
        } else {
            System.out.println("登录成功，欢迎使用！");
            // 将登录成功的用户信息放入session对象中实现多个请求共享
            request.getSession().setAttribute("user", user);
            // 实现客户端跳转
            response.sendRedirect("main.jsp");
        }
    }
}
